<template>
  <div>
    <el-dialog
      top="1vh"
      width="55%"
      :title="title"
      destroy-on-close
      append-to-body
      v-if="visible"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :visible.sync="visible"
      @close="handleEditReset"
    >
      <div class="dialog-content">
        <el-tabs v-model="activeName" type="card" :before-leave="handleBeforeLeave">
          <el-tab-pane label="系统值" name="systemFields"> </el-tab-pane>
          <el-tab-pane label="打印时输入" name="printFields"></el-tab-pane>
          <avue-form :option="option" v-show="activeName === 'systemFields'" ref="editForm" v-model="form">
            <template slot="querySql">
              <el-input type="textarea" :rows="6" placeholder="请输入主sql" v-model="form.querySql" :disabled="dialogType === 'view'"> </el-input>
              <p class="mes-color">
                注：在数据源sql中，您可以使用后台提供的每个打印请求附带的自身筛选参数来进行数据的筛选，借助mybatis占位符的格式 #{prop} 去使用这些筛选参数，如：select id from
                mfg_work_order where id = #{workOrderId}。
              </p>
            </template>
          </avue-form>
          <avue-crud
            :option="tableOption"
            v-show="activeName === 'printFields'"
            ref="editCrud"
            :permission="permissionList"
            v-model="tableFrom"
            :data="form.fieldList"
            @row-update="rowUpdate"
            @row-save="rowSave"
            @row-del="rowDel"
            @select="handleSetDefaultValue"
            @selection-change="selectionChange"
          >
            <template slot="dicDataForm">
              <el-input placeholder="请选择选项" v-model="tableFrom.dicData">
                <i slot="suffix" @click="handleSelectValue" class="el-input__icon el-icon-edit">编辑 </i>
              </el-input>
            </template>
          </avue-crud>
        </el-tabs>
      </div>
      <div slot="footer">
        <el-button size="small" icon="el-icon-delete" @click="handleEditReset">取消</el-button>
        <el-button size="small" type="primary" icon="el-icon-check" @click="handleEditSubmit" v-if="dialogType !== 'view'">保存</el-button>
      </div>
    </el-dialog>

    <el-dialog
      top="5vh"
      width="35%"
      title="编辑选项"
      destroy-on-close
      append-to-body
      v-if="optionVisible"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :visible.sync="optionVisible"
      @close="handleEditReset"
    >
      <avue-crud
        ref="optionCrud"
        :data="optionData"
        :option="selectOption"
        class="edit-curd"
        @row-save="optionRowSave"
        @row-update="optionRowUpdate"
        @row-del="optionRowDel"
        @row-dblclick="handleRowDBLClick"
      >
        <template slot="defaultValue" slot-scope="{ row }">
          <el-checkbox v-model="selectValue" :true-label="row.value"></el-checkbox>
        </template>
      </avue-crud>

      <p class="mes-color">注：勾选的选项为该下拉列表的默认值</p>
      <div slot="footer">
        <el-button size="small" icon="el-icon-delete" @click="handleClose">取消</el-button>
        <el-button size="small" type="primary" icon="el-icon-check" @click="handleSave">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addSubmit as save, getDetail } from '@/api/labelManagement/tagDataSource';

export default {
  name: 'editDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    dialogType: {
      type: String,
      default: 'add'
    }
  },
  computed: {
    title() {
      if (this.dialogType === 'add') {
        return '新增';
      } else if (this.dialogType === 'edit') {
        return '编辑';
      } else {
        return '详情';
      }
    },
    isDisabled() {
      return this.dialogType === 'view';
    },
    permissionList() {
      return {
        addBtn: !this.isDisabled,
        editBtn: !this.isDisabled,
        delBtn: !this.isDisabled
      };
    }
  },
  watch: {
    'tableFrom.controlType'(nval, oval) {
      if (nval && oval && nval !== oval) {
        this.tableFrom.defaultValue = '';
      }
    },
    dialogType(val) {
      if (val === 'view') {
        const col = this._cloneDeep(this.option.column);
        const column = col.map((item) => ({ ...item, disabled: true }));
        this.$set(this.option, 'column', column);
      } else {
        const col = this._cloneDeep(this.option.column);
        const column = col.map((item) => ({ ...item, disabled: false }));
        this.$set(this.option, 'column', column);
      }
    }
  },
  data() {
    return {
      activeName: 'systemFields',
      selectValue: '',
      tableFrom: {},
      option: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 120,
        column: [
          {
            label: '数据名称',
            prop: 'name',
            search: true,
            maxlength: 30,
            rules: [
              {
                required: true,
                message: '请输入数据名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '数据编码',
            prop: 'code',
            rules: [
              {
                required: true,
                message: '请输入数据编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '数据描述',
            prop: 'remark',
            rules: [
              {
                required: true,
                message: '请输入数据描述',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '数据源类型',
            prop: 'type',
            type: 'select',
            dicData: [
              { label: '标签模板', value: 'LABEL_TEMPLATE' },
              { label: '序列号规则', value: 'SEQUENCE_DEFINITION' }
            ],
            rules: [{ required: true, message: '请选择数据源类型', trigger: 'change' }]
          },
          {
            label: '是否可用',
            search: true,
            prop: 'status',
            type: 'switch',
            value: 2,
            dataType: 'number',
            align: 'center',
            dicData: [
              {
                label: '否',
                value: 2
              },
              {
                label: '是',
                value: 1
              }
            ]
            // slot: true,
            // rules: [
            //   {
            //     required: true,
            //     message: '请选择是否可用',
            //     trigger: 'blur'
            //   }
            // ]
          },
          {
            label: '主SQL',
            prop: 'querySql',
            type: 'textarea',
            slot: true,
            span: 24,
            maxRows: 6,
            minRows: 6
          }
        ]
      },
      selectionList: [],
      tableOption: {
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        labelWidth: 110,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: true,
        viewBtn: false,
        viewBtnText: '详情',
        viewTitle: '详情',
        editBtn: true,
        delBtn: true,
        refreshBtn: false,
        excelBtn: false,
        selection: true,
        dialogDrag: false, // 开启拖拽功能
        dialogClickModal: false,
        columnBtn: false,
        column: [
          {
            label: '字段',
            prop: 'field',
            labelTip: '代表key，需与标签模板字段相对',
            rules: [
              {
                required: true,
                message: '请输入字段',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '名称',
            prop: 'name',
            labelTip: '代表显示值',
            rules: [
              {
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '控件类型',
            prop: 'controlType',
            type: 'select',
            value: 'input',
            clearable: false,
            dicData: [
              { label: '输入框', value: 'input' },
              { label: '文本框', value: 'textarea' },
              { label: '数字输入框', value: 'number' },
              { label: '下拉列表', value: 'select' },
              { label: '时间选择器(年月日时分秒)', value: 'datetime' },
              { label: '日期选择器(年月日)', value: 'date' }
            ],
            control: (val, form) => {
              return {
                defaultValue: {
                  type: val,
                  disabled: val === 'select'
                }
              };
            }
          },
          {
            label: '选项',
            prop: 'dicData',
            control: (val, form) => {
              const rules = [{ required: form.isRequired, message: '请输入选项', trigger: 'change' }];
              if (form.controlType === 'select') {
                return {
                  dicData: {
                    display: true,
                    rules
                  }
                };
              } else {
                return {
                  dicData: {
                    display: false,
                    rules
                  }
                };
              }
            }
          },
          {
            label: '默认值',
            prop: 'defaultValue',
            formatter: (row, column, cellValue, index) => {
              if (row.controlType === 'datetime') {
                return this.$moment(column).format('yyyy-MM-DD HH:MM:SS');
              } else if (row.controlType === 'date') {
                return this.$moment(column).format('yyyy-MM-DD');
              } else {
                return column;
              }
            }
          },
          {
            label: '是否必填',
            prop: 'isRequired',
            type: 'switch',
            value: true,
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ]
          }
        ]
      },
      form: { fieldList: [] },
      optionVisible: false,
      optionData: [],
      selectOption: {
        addRowBtn: true,
        addBtn: false,
        cellBtn: true,
        refreshBtn: false,
        columnBtn: false,
        editBtn: false,
        menuWidth: 250,
        selection: false,
        column: [
          {
            label: '',
            prop: 'defaultValue',
            width: 60,
            hide: false
          },
          {
            label: '选项值',
            prop: 'value',
            cell: true,
            rules: [
              {
                required: true,
                message: '请输入选项值',
                trigger: 'blur'
              }
            ],
            blur: ({ column, value }) => {
              console.log(column, value);
            }
          }
        ]
      }
    };
  },
  methods: {
    async getDetail(id) {
      try {
        const res = await getDetail(id);
        const data = res.data.data;
        this.form = data;
      } catch (e) {
        console.warn(e);
      }
    },
    handleEditReset() {
      this.form = {
        fieldList: []
      };
      this.activeName = 'systemFields';
      this.$emit('update:visible', false);
      this.$emit('closeDialog');
    },
    rowSave(row, done, loading) {
      try {
        const fieldList = this.form.fieldList || [];
        const fieldArray = fieldList.map((item) => item.field);
        if (fieldArray.includes(row.field)) {
          this.$message.error('字段值重复，请修改');
          loading();
        } else {
          fieldList.push(row);
          this.$set(this.form, 'fieldList', fieldList);
          done();
        }
      } catch (e) {
        console.log(e);
      }
    },
    rowUpdate(row, index, done, loading) {
      const fieldList = this._cloneDeep(this.form.fieldList || []);
      fieldList.splice(index, 1);
      const fieldArray = fieldList.map((item) => item.field);
      if (fieldArray.includes(row.field)) {
        this.$message.error('字段值重复，请修改');
        loading();
      } else {
        fieldList.splice(index, 0, row);
        this.$set(this.form, 'fieldList', fieldList);
        done();
      }
    },
    rowDel(row, index, done) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const fieldList = this._cloneDeep(this.form.fieldList || []);
        fieldList.splice(index, 1);
        this.$set(this.form, 'fieldList', fieldList);
        done();
      });
    },
    selectionChange(list) {
      this.selectionList = list;
    },

    handleBeforeLeave(activeName, oldActiveName) {
      if (oldActiveName === 'systemFields' && this.form.type === 'SEQUENCE_DEFINITION') {
        this.$message.warning('数据源类型为“序列号规则”的数据源，不可配置打印时输入');
        return false;
      } else {
        return true;
      }
    },
    handleSelectValue() {
      this.selectValue = this.tableFrom.defaultValue || '';
      let data = [];
      if (this.tableFrom.dicData) {
        data = this.tableFrom.dicData.split(',').map((i) => ({ value: i }));
      }
      this.optionData = data;
      this.optionVisible = true;
    },
    handleSetDefaultValue(selection, row) {
      // this.$refs.optionCrud.clearSelection();
      this.$nextTick(() => {
        this.$refs.optionCrud.toggleSelection([selection]);
      });
      console.log(selection, row);
    },
    handleEditSubmit() {
      try {
        this.$refs.editForm.validate((valid, done, msg) => {
          if (valid) {
            save(this.form)
              .then(() => {
                this.form = {
                  fieldList: []
                };
                this.$emit('update:visible', false);
                this.$emit('closeDialog');
                done();
              })
              .catch((err) => {
                done();
              });
          } else {
            this.activeName = 'systemFields';
          }
        });
      } catch (e) {
        console.log(e);
      }
    },
    handleRowDBLClick(row, event) {
      row.$cellEdit = true;
    },
    handleClose() {
      this.optionData = [];
      this.optionVisible = false;
    },
    optionRowSave(form, done) {
      console.log('optionRowSave');
      done();
    },
    handleSave() {
      const str = this.optionData.map((i) => i.value).join(',');
      this.tableFrom.dicData = str;
      this.tableFrom.defaultValue = this.selectValue || '';
      this.handleClose();
    },
    optionRowUpdate(form, index, done, loading) {
      console.log('optionRowUpdate');
      done();
    },
    optionRowDel(row, index) {
      this.optionData.splice(index, 1);
    }
  }
};
</script>

<style scoped lang="scss">
.dialog-content {
  height: calc(100vh - 270px);
  overflow-y: scroll;
}
.mes-color {
  color: red;
}
.el-input__icon {
  width: 56px;
  color: #0a84ff;
  cursor: pointer;
}

.edit-curd {
  width: 90%;
  padding-top: 15px;
  ::v-deep .avue-crud__tip {
    display: none;
  }
}
</style>
